<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        @finish="handleSubmit"
      >
        <div class="option-column">
          <div class="column-title">客户信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="客户名称" name="name">
                <a-select
                  v-model:value="formState.customer_id"
                  placeholder="选择客户"
                  @change="handleCustomerChange"
                >
                  <a-select-option
                    v-for="item in customerList"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="客户编号" name="no">
                <a-input
                  :disabled="true"
                  v-model:value="formState.no"
                  placeholder="选择客户后自动填充"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="客户分类" name="customer_type_id">
                <a-input
                  v-model:value="formState.customer_type_name"
                  :disabled="true"
                  placeholder="选择客户后自动填充"
                ></a-input>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="状态">
                <a-input
                  v-model:value="formState.customer_status_name"
                  :disabled="true"
                  placeholder="选择客户后自动填充"
                ></a-input>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="所在地区">
                <a-input
                  v-model:value="formState.address"
                  :disabled="true"
                  placeholder="选择客户后自动填充"
                ></a-input>
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">经销商信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="经销商">
                <a-select
                  :disabled="true"
                  v-model:value="formState.dealer_id"
                  placeholder="选择客户后自动填充"
                >
                  <a-select-option
                    v-for="item in dealerList"
                    :key="item.value"
                    :value="item.dealer_id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="销售">
                <a-input
                  v-model:value="formState.sales_name"
                  placeholder="请输入销售"
                />
              </a-form-item>
            </div>
            <!-- 去经销商那里编辑 -->
            <!-- <div class="content-item">
              <a-form-item label="销售联系方式">
                <a-input
                  v-model:value="formState.phone"
                  placeholder="请输入销售联系方式"
                />
              </a-form-item>
            </div> -->
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">订单信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="合同开始日期">
                <a-date-picker
                  v-model:value="formState.contract_begin_date"
                  format="YYYY-MM-DD HH:mm:ss"
                  :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="合同期限">
                <a-input
                  v-model:value="formState.contract_months"
                  suffix="个月"
                  placeholder="请填写数字"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="订单状态">
                <a-select
                  v-model:value="formState.order_status_id"
                  placeholder="请选择订单状态"
                >
                  <a-select-option
                    v-for="item in statusList"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">硬件</div>
          <div
            class="column-content"
            v-for="(item, index) in deviceList"
            :key="index"
          >
            <div class="content-item">
              <a-form-item label="设备">
                <a-select v-model:value="item.device_id" placeholder="请选择">
                  <a-select-option
                    v-for="item in deviceOptions"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="数量">
                <a-input v-model:value="item.amount" placeholder="请填写数字" />
              </a-form-item>
              <MinusCircleOutlined
                class="delete-button"
                @click="deleteDevice(index)"
              />
            </div>
          </div>
          <div class="column-footer">
            <a-button type="dashed" :icon="h(PlusOutlined)" @click="addDevice"
              >添加设备</a-button
            >
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">软件</div>
          <!-- app接口没有数据 -->
          <a-checkbox-group
            v-if="softwareOptions.length"
            v-model:value="software"
            name="checkboxgroup"
            :options="softwareOptions"
          />
          <p v-else>暂无</p>
        </div>
        <div class="option-column">
          <div class="column-title">
            虚拟实验（已选{{ state.selectedRowKeys.length }}）
          </div>

          <a-table
            class="table-inner"
            :pagination="false"
            :scroll="{ y: 500 }"
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="experimentOptions"
            rowKey="experiment_id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex == 'ai_enabled'">
                <div class="status-text">
                  {{ column.ai_enabled ? "已启用" : "未启用" }}
                </div>
              </template>
              <template v-if="column.dataIndex == 'virtual_enabled'">
                <div class="status-text">
                  {{ column.virtual_enabled ? "已启用" : "未启用" }}
                </div>
              </template>
              <template v-if="column.dataIndex == 'twin_abled'">
                <div class="status-text">
                  {{ column.twin_abled ? "已启用" : "未启用" }}
                </div>
              </template>
              <template v-if="column.dataIndex == 'use_months'">
                <a-input
                  v-model:value="record.use_months"
                  placeholder="请填写数字"
                  suffix="个月"
                />
              </template>
            </template>
          </a-table>
        </div>
        <!-- <div class="option-column">
          <div class="column-title">直播功能</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="开启直播功能">
                <a-switch v-model:checked="formState.live_enabled" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="剩余直播时长">
                <a-input
                  v-model:value="formState.live_hours"
                  suffix="小时"
                  placeholder="请填写数字"
                />
              </a-form-item>
            </div>
          </div>
        </div> -->
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" htmlType="submit"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import api from "@/api";
import router from "@/routers";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, h, onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
const query = computed(() => route.query);
const pageType = computed(() => (query.value.id ? "edit" : "add"));
const formState = ref({
  customer_id: "",
  no: "",
  customer_type_id: "",
  customer_status_id: "",
  city_id: "",
  userName: "",
  position: "",
  phone: "",
  telephone: "",
  email: "",
  dealer: "",
  salesperson: "",
  contract_begin_date: null,
  contract_months: "",
  order_status_id: "",
  sales_name: "",
  dealer_id: "",
  customer_type_name: "",
  customer_status_name: "",
  address: "",
  remark: "",
  live_enabled: false,
  live_hours: 0,
  enabled: true,
});
const zoneoList = [];
const customerList = ref([]);
const dealerList = ref([]);
const deviceList = ref([]);
const deviceOptions = ref([]);
const softwareOptions = ref([]);
const software = ref([]);
const experimentOptions = ref([]);
const experiment = ref([]);

const addDevice = () => {
  deviceList.value.push({
    device_id: "",
    amount: 0,
  });
};

const deleteDevice = (index) => {
  deviceList.value.splice(index, 1);
};

const state = reactive({
  selectedRowKeys: [],
  // Check here to configure the default column
  loading: false,
});

const onSelectChange = (selectedRowKeys, selectedRows) => {
  state.selectedRowKeys = selectedRowKeys;
  state.selectedRows = selectedRows;
};

// 获取实验使用期限
const getExperimentMonths = (experimentId) => {
  const experiment = experimentOptions.value.find(
    (exp) => exp.experiment_id === experimentId
  );
  return experiment?.use_months || 0;
};
const columns = ref([
  {
    dataIndex: "name",
    title: "实验名称",
    width: 110,
    fixed: "left",
  },
  {
    dataIndex: "use_months",
    title: "使用期限",
    width: 110,
  },
  {
    dataIndex: "ai_enabled",
    title: "AI测评",
    width: 90,
  },
  {
    dataIndex: "virtual_enabled",
    title: "模拟仿真",
    width: 90,
  },
  {
    dataIndex: "twin_abled",
    title: "数字孪生",
    width: 90,
  },
]);

const rules = ref({
  customer_id: [
    {
      required: true,
      message: "请选择客户",
      trigger: "blur",
    },
  ],
});
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));
const statusList = ref([]);
/**
 * 页面初始化 - 获取基础数据和编辑数据
 */
onMounted(async () => {
  try {
    state.loading = true;

    // 并行获取所有基础选项数据
    await Promise.all([
      // 获取客户选项
      api
        .apiCustomerOptionsPost({})
        .then((res) => (customerList.value = res.data)),
      // 获取经销商选项
      api.apiUserMyDealersPost({}).then((res) => (dealerList.value = res.data)),
      // 获取设备选项
      api
        .apiDeviceOptionsPost({})
        .then((res) => (deviceOptions.value = res.data)),
      // 获取订单状态选项
      api
        .apiOrderStatusOptionsPost({})
        .then((res) => (statusList.value = res.data)),
      // 获取软件选项
      api
        .apiAppPagedListPost({ args: { current: 1, pageSize: 999 } })
        .then((res) => {
          softwareOptions.value = res.data.data.map((item) => ({
            label: item.name,
            value: item.app_id,
          }));
        }),
      // 获取实验选项
      api
        .apiExperimentPagedListPost({
          args: { current: 1, pageSize: 999 },
        })
        .then((res) => {
          experimentOptions.value = res.data.data.map((item) => ({
            ...item,
            use_months: item.use_months || 0,
          }));
          total.value = res.data.total;
        }),
    ]);

    // 如果是编辑模式，获取订单数据
    if (pageType.value === "edit") {
      await getData();
    }

    console.log("页面初始化完成，基础数据加载成功");
  } catch (error) {
    console.error("页面初始化失败:", error);
    message.error("页面初始化失败，请刷新重试");
  } finally {
    state.loading = false;
  }
});

/**
 * 获取订单数据 - 编辑模式使用
 * 获取主表和子表的完整数据
 */
const getData = async () => {
  try {
    state.loading = true;

    // 获取订单主表数据
    const res = await api.apiOrderContractFetchModelPost({
      order_id: query.value.id,
    });

    if (!res.data) {
      message.error("订单数据不存在");
      return;
    }

    // 设置主表数据
    formState.value = {
      ...res.data,
      // 转换日期格式
      contract_begin_date: res.data.contract_begin_date
        ? dayjs(res.data.contract_begin_date)
        : null,
    };

    // 获取客户详细信息
    await getCustomerInfo(res.data.customer_id);

    // 设置软件子表数据
    software.value = res.data.apps.map((item) => item.app_id);

    // 设置设备子表数据
    deviceList.value = res.data.devices.map((item) => ({
      device_id: item.device_id,
      amount: item.amount ? Number(item.amount) : 0,
    }));

    // 设置实验子表数据
    state.selectedRowKeys = res.data.experiments.map(
      (item) => item.experiment_id
    );
    state.selectedRows = res.data.experiments.map((item) => ({
      experiment_id: item.experiment_id,
      use_months: item.use_months ? Number(item.use_months) : 0,
      ...item.experiment,
    }));

    console.log("订单数据获取成功:", {
      main: formState.value,
      software: software.value,
      devices: deviceList.value,
      experiments: state.selectedRows,
    });
  } catch (error) {
    console.error("获取订单数据失败:", error);
    message.error("获取订单数据失败，请重试");
  } finally {
    state.loading = false;
  }
};

/**
 * 客户选择变更处理
 * 当用户选择客户时，自动填充客户相关信息
 * @param {string} value 选中的客户ID
 */
const handleCustomerChange = async (value) => {
  if (!value) {
    // 清空客户相关信息
    resetCustomerInfo();
    return;
  }

  try {
    console.log("获取客户信息，客户ID:", value);

    // 获取客户详细信息
    const res = await api.apiCustomerFetchModelPost({ customer_id: value });

    if (!res.data) {
      message.error("客户信息不存在");
      return;
    }

    // 自动填充客户相关信息
    formState.value.no = res.data.no;
    formState.value.customer_type_id = res.data.customer_type_id;
    formState.value.customer_type_name = res.data.customer_type_name;
    formState.value.customer_status_id = res.data.customer_status_id;
    formState.value.customer_status_name = res.data.customer_status_name;
    formState.value.city_id = res.data.city_id;
    formState.value.address = `${res.data.province_name || ""} ${
      res.data.city_name || ""
    }`.trim();

    console.log("客户信息填充完成:", res.data);
  } catch (error) {
    console.error("获取客户信息失败:", error);
    message.error("获取客户信息失败，请重试");
  }
};

/**
 * 获取客户详细信息 - 编辑模式使用
 * 用于编辑时填充客户相关信息
 * @param {string} value 客户ID
 */
const getCustomerInfo = async (value) => {
  try {
    console.log("获取客户详细信息，客户ID:", value);

    const res = await api.apiCustomerFetchModelPost({ customer_id: value });

    if (!res.data) {
      console.warn("客户信息不存在，客户ID:", value);
      return;
    }

    // 填充客户相关信息
    formState.value.dealer_id = res.data.dealer_id;
    formState.value.sales_name = res.data.sales_name;
    formState.value.no = res.data.no;
    formState.value.customer_type_id = res.data.customer_type_id;
    formState.value.customer_type_name = res.data.customer_type_name;
    formState.value.customer_status_id = res.data.customer_status_id;
    formState.value.customer_status_name = res.data.customer_status_name;
    formState.value.city_id = res.data.city_id;
    formState.value.address = `${res.data.province_name || ""} ${
      res.data.city_name || ""
    }`.trim();

    console.log("客户详细信息获取完成:", res.data);
  } catch (error) {
    console.error("获取客户详细信息失败:", error);
    message.error("获取客户详细信息失败");
  }
};

/**
 * 重置客户相关信息
 * 清空客户相关的所有字段
 */
const resetCustomerInfo = () => {
  formState.value.no = "";
  formState.value.customer_type_id = "";
  formState.value.customer_type_name = "";
  formState.value.customer_status_id = "";
  formState.value.customer_status_name = "";
  formState.value.city_id = "";
  formState.value.address = "";
  formState.value.dealer_id = "";
  formState.value.sales_name = "";
};

/**
 * 表单重置
 * 清空所有表单数据并返回上一页
 */
const resetForm = () => {
  // 清空表单状态
  formState.value = {
    customer_id: "",
    no: "",
    customer_type_id: "",
    customer_status_id: "",
    city_id: "",
    dealer_id: "",
    sales_name: "",
    contract_begin_date: null,
    contract_months: "",
    order_status_id: "",
    live_enabled: false,
    live_hours: 0,
  };

  // 清空子表数据
  deviceList.value = [];
  software.value = [];
  state.selectedRowKeys = [];
  state.selectedRows = [];

  // 返回上一页
  router.go(-1);
};

/**
 * 表单提交处理 - 新增或更新订单
 * 按照主从表设计：先操作主表，再操作子表
 */
const handleSubmit = async () => {
  try {
    state.loading = true;

    if (pageType.value === "edit") {
      // 编辑模式：更新订单
      await handleUpdateOrder();
    } else {
      // 新增模式：创建订单
      await handleCreateOrder();
    }
  } catch (error) {
    console.error("订单操作失败:", error);
    message.error("操作失败，请重试");
  } finally {
    state.loading = false;
  }
};

/**
 * 新增订单 - 先创建主表，再循环创建子表
 */
const handleCreateOrder = async () => {
  try {
    console.log("=== 开始新增订单 ===");

    // 1. 创建订单主表
    console.log("步骤1: 创建订单主表...");
    const orderResult = await api.apiOrderContractCreateOrderContractPost({
      customer_id: formState.value.customer_id,
      no: formState.value.no,
      contract_begin_date: formState.value.contract_begin_date,
      contract_months: formState.value.contract_months,
      order_status_id: formState.value.order_status_id,
      live_enabled: formState.value.live_enabled,
      live_hours: formState.value.live_hours,
      remark: formState.value.remark,
      enabled: formState.value.enabled,
      // 客户相关信息
      customer: {
        customer_id: formState.value.customer_id,
        customer_type_id: formState.value.customer_type_id,
        customer_status_id: formState.value.customer_status_id,
        city_id: formState.value.city_id,
        sales_name: formState.value.sales_name,
        dealer_id: formState.value.dealer_id,
      },
    });

    if (!orderResult.data?.order_id) {
      throw new Error("创建订单主表失败：未获取到订单ID");
    }

    const orderId = orderResult.data.order_id;
    console.log("✅ 订单主表创建成功，订单ID:", orderId);

    // 2. 循环创建子表数据
    console.log("步骤2: 开始创建子表数据...");
    await createSubTables(orderId);

    console.log("=== 订单创建完成 ===");
    message.success("订单创建成功");
    resetForm();
  } catch (error) {
    console.error("❌ 创建订单失败:", error);
    message.error(`创建订单失败: ${error.message || "未知错误"}`);
    throw error; // 重新抛出错误，让上层处理
  }
};

/**
 * 更新订单 - 先获取现有数据，合并表单数据，再更新主表，最后处理子表
 */
const handleUpdateOrder = async () => {
  try {
    const orderId = query.value.id;
    console.log("=== 开始更新订单，订单ID:", orderId);

    // 1. 先获取现有的订单数据
    console.log("步骤1: 获取现有订单数据...");
    const existingOrderResult = await api.apiOrderContractFetchModelPost({
      order_id: orderId,
    });

    if (!existingOrderResult.data) {
      throw new Error("订单数据不存在");
    }

    const existingOrder = existingOrderResult.data;
    console.log("获取到的现有订单数据:", existingOrder);

    // 2. 将表单数据合并到现有模型中
    console.log("步骤2: 合并表单数据到现有模型...");
    const mergedOrderData = {
      ...existingOrder, // 保留所有现有字段
      // 用表单数据覆盖需要更新的字段
      customer_id: formState.value.customer_id,
      no: formState.value.no,
      contract_begin_date: formState.value.contract_begin_date,
      contract_months: formState.value.contract_months,
      order_status_id: formState.value.order_status_id,
      live_enabled: formState.value.live_enabled,
      live_hours: formState.value.live_hours,
      remark: formState.value.remark,
      enabled: formState.value.enabled,
      // 客户相关信息
      customer: {
        ...existingOrder.customer, // 保留现有客户信息
        customer_id: formState.value.customer_id,
        customer_type_id: formState.value.customer_type_id,
        customer_status_id: formState.value.customer_status_id,
        city_id: formState.value.city_id,
        sales_name: formState.value.sales_name,
        dealer_id: formState.value.dealer_id,
      },
    };

    console.log("合并后的订单数据:", mergedOrderData);

    // 3. 更新订单主表
    console.log("步骤3: 更新订单主表...");
    await api.apiOrderContractUpdatePost(mergedOrderData);

    console.log("✅ 订单主表更新成功");

    // 4. 删除所有子表记录
    console.log("步骤4: 删除所有子表记录...");
    await deleteSubTables(orderId);

    // 5. 重新创建子表记录
    console.log("步骤5: 重新创建子表记录...");
    await createSubTables(orderId);

    console.log("=== 订单更新完成 ===");
    message.success("订单更新成功");
    resetForm();
  } catch (error) {
    console.error("❌ 更新订单失败:", error);
    message.error(`更新订单失败: ${error.message || "未知错误"}`);
    throw error;
  }
};

/**
 * 创建子表数据 - 设备、软件、实验
 * 按照主从表设计，循环创建每个子表记录
 * @param {string} orderId 订单ID
 */
const createSubTables = async (orderId) => {
  try {
    console.log("=== 开始创建子表数据 ===");
    console.log("订单ID:", orderId);

    // 1. 创建设备子表
    console.log("步骤2.1: 创建设备子表...");
    await createDeviceSubTable(orderId);

    // 2. 创建软件子表
    console.log("步骤2.2: 创建软件子表...");
    await createSoftwareSubTable(orderId);

    // 3. 创建实验子表
    console.log("步骤2.3: 创建实验子表...");
    await createExperimentSubTable(orderId);

    console.log("✅ 所有子表创建完成");
  } catch (error) {
    console.error("❌ 创建子表失败:", error);
    throw new Error(`创建子表失败: ${error.message}`);
  }
};

/**
 * 创建设备子表 - 循环创建每个设备记录
 * @param {string} orderId 订单ID
 */
const createDeviceSubTable = async (orderId) => {
  if (!deviceList.value.length) {
    console.log("⚠️ 无设备数据，跳过设备子表创建");
    return;
  }

  console.log(`📱 开始创建设备子表，设备数量: ${deviceList.value.length}`);
  console.log("设备列表:", deviceList.value);

  // 循环创建每个设备记录
  for (let i = 0; i < deviceList.value.length; i++) {
    const device = deviceList.value[i];

    // 验证设备数据
    if (!device.device_id || !device.amount) {
      console.warn(`⚠️ 跳过无效设备数据 [${i + 1}]:`, device);
      continue;
    }

    try {
      console.log(`📱 创建设备记录 [${i + 1}/${deviceList.value.length}]:`, {
        device_id: device.device_id,
        amount: device.amount,
      });

      // 调用API创建设备子表记录
      const result = await api.apiOrderDeviceCreatePost({
        order_id: orderId,
        device_id: device.device_id,
        amount: Number(device.amount),
      });

      console.log(`✅ 设备记录 [${i + 1}] 创建成功:`, result);
    } catch (error) {
      console.error(`❌ 设备记录 [${i + 1}] 创建失败:`, error);
      throw new Error(`创建设备记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 设备子表创建完成");
};

/**
 * 创建软件子表 - 循环创建每个软件记录
 * @param {string} orderId 订单ID
 */
const createSoftwareSubTable = async (orderId) => {
  if (!software.value.length) {
    console.log("⚠️ 无软件数据，跳过软件子表创建");
    return;
  }

  console.log(`💾 开始创建软件子表，软件数量: ${software.value.length}`);
  console.log("软件ID列表:", software.value);

  // 循环创建每个软件记录
  for (let i = 0; i < software.value.length; i++) {
    const appId = software.value[i];

    try {
      console.log(`💾 创建软件记录 [${i + 1}/${software.value.length}]:`, {
        order_id: orderId,
        app_id: appId,
      });

      // 先检查记录是否已存在
      const existsResult = await api.apiOrderAppExistsPost({
        order_id: orderId,
        app_id: appId,
      });

      if (existsResult.data) {
        // 记录已存在，先删除再创建
        console.log(`⚠️ 软件记录 [${i + 1}] 已存在，先删除`);
        await api.apiOrderAppDeletePost({
          order_id: orderId,
          app_id: appId,
        });
        console.log(`✅ 已删除现有软件记录 [${i + 1}]`);
      }

      // 调用API创建软件子表记录
      const result = await api.apiOrderAppCreatePost({
        order_id: orderId,
        app_id: appId,
      });

      console.log(`✅ 软件记录 [${i + 1}] 创建成功:`, result);
    } catch (error) {
      console.error(`❌ 软件记录 [${i + 1}] 创建失败:`, error);
      throw new Error(`创建软件记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 软件子表创建完成");
};

/**
 * 创建实验子表 - 循环创建每个实验记录
 * @param {string} orderId 订单ID
 */
const createExperimentSubTable = async (orderId) => {
  if (!state.selectedRowKeys.length) {
    console.log("⚠️ 无实验数据，跳过实验子表创建");
    return;
  }

  console.log(`🧪 开始创建实验子表，实验数量: ${state.selectedRowKeys.length}`);
  console.log("实验ID列表:", state.selectedRowKeys);

  // 循环创建每个实验记录
  for (let i = 0; i < state.selectedRowKeys.length; i++) {
    const experimentId = state.selectedRowKeys[i];

    // 获取实验详细信息
    const experimentData = experimentOptions.value.find(
      (exp) => exp.experiment_id === experimentId
    );

    if (!experimentData) {
      console.warn(`⚠️ 跳过无效实验数据 [${i + 1}]:`, experimentId);
      continue;
    }

    try {
      console.log(
        `🧪 创建实验记录 [${i + 1}/${state.selectedRowKeys.length}]:`,
        {
          experiment_id: experimentId,
          use_months: experimentData.use_months || 0,
        }
      );

      // 调用API创建实验子表记录
      const result = await api.apiOrderExperimentCreatePost({
        order_id: orderId,
        experiment_id: experimentId,
        use_months: Number(experimentData.use_months || 0),
      });

      console.log(`✅ 实验记录 [${i + 1}] 创建成功:`, result);
    } catch (error) {
      console.error(`❌ 实验记录 [${i + 1}] 创建失败:`, error);
      throw new Error(`创建实验记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 实验子表创建完成");
};

/**
 * 删除子表数据
 * 按照主从表设计，循环删除每个子表记录
 * @param {string} orderId 订单ID
 */
const deleteSubTables = async (orderId) => {
  try {
    console.log("=== 开始删除子表数据 ===");
    console.log("订单ID:", orderId);

    // 获取当前订单的子表数据
    console.log("步骤2.1: 获取当前订单的子表数据...");
    const orderData = await api.apiOrderContractFetchModelPost({
      order_id: orderId,
    });

    if (!orderData.data) {
      console.log("⚠️ 订单数据不存在，无需删除子表");
      return;
    }

    console.log("获取到的订单数据:", orderData.data);

    // 1. 删除设备子表
    console.log("步骤2.2: 删除设备子表...");
    await deleteDeviceSubTable(orderData.data.devices);

    // 2. 删除软件子表
    console.log("步骤2.3: 删除软件子表...");
    await deleteSoftwareSubTable(orderData.data.apps, orderId);

    // 3. 删除实验子表
    console.log("步骤2.4: 删除实验子表...");
    await deleteExperimentSubTable(orderData.data.experiments);

    console.log("✅ 所有子表删除完成");
  } catch (error) {
    console.error("❌ 删除子表失败:", error);
    throw new Error(`删除子表失败: ${error.message}`);
  }
};

/**
 * 删除设备子表 - 循环删除每个设备记录
 * @param {Array} devices 设备列表
 */
const deleteDeviceSubTable = async (devices) => {
  if (!devices?.length) {
    console.log("⚠️ 无设备数据，跳过设备子表删除");
    return;
  }

  console.log(`📱 开始删除设备子表，设备数量: ${devices.length}`);
  console.log("设备列表:", devices);

  // 循环删除每个设备记录
  for (let i = 0; i < devices.length; i++) {
    const device = devices[i];

    if (!device.order_device_id) {
      console.warn(`⚠️ 跳过无效设备记录 [${i + 1}]:`, device);
      continue;
    }

    try {
      console.log(`📱 删除设备记录 [${i + 1}/${devices.length}]:`, {
        order_device_id: device.order_device_id,
        device_id: device.device_id,
        amount: device.amount,
      });

      // 调用API删除设备子表记录
      const result = await api.apiOrderDeviceDeletePost({
        order_device_id: device.order_device_id,
      });

      console.log(`✅ 设备记录 [${i + 1}] 删除成功:`, result);
    } catch (error) {
      console.error(`❌ 设备记录 [${i + 1}] 删除失败:`, error);
      throw new Error(`删除设备记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 设备子表删除完成");
};

/**
 * 删除软件子表 - 循环删除每个软件记录
 * @param {Array} apps 软件列表
 * @param {string} orderId 订单ID
 */
const deleteSoftwareSubTable = async (apps, orderId) => {
  if (!apps?.length) {
    console.log("⚠️ 无软件数据，跳过软件子表删除");
    return;
  }

  console.log(`💾 开始删除软件子表，软件数量: ${apps.length}`);
  console.log("软件列表:", apps);

  // 循环删除每个软件记录
  for (let i = 0; i < apps.length; i++) {
    const app = apps[i];

    // if (!app.order_app_id) {
    //   console.warn(`⚠️ 跳过无效软件记录 [${i + 1}]:`, app);
    //   continue;
    // }
    if (!app.app_id) {
      console.warn(`⚠️ 跳过无效软件记录 [${i + 1}]:`, app);
      continue;
    }

    try {
      console.log(`💾 删除软件记录 [${i + 1}/${apps.length}]:`, {
        order_id: orderId,
        app_id: app.app_id,
      });

      // 先检查记录是否存在
      const existsResult = await api.apiOrderAppExistsPost({
        order_id: orderId,
        app_id: app.app_id,
      });

      if (existsResult.data) {
        // 记录存在，执行删除
        const result = await api.apiOrderAppDeletePost({
          order_id: orderId,
          app_id: app.app_id,
        });

        console.log(`✅ 软件记录 [${i + 1}] 删除成功:`, result);
      } else {
        console.log(`⚠️ 软件记录 [${i + 1}] 不存在，跳过删除`);
      }
    } catch (error) {
      console.error(`❌ 软件记录 [${i + 1}] 删除失败:`, error);
      throw new Error(`删除软件记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 软件子表删除完成");
};

/**
 * 删除实验子表 - 循环删除每个实验记录
 * @param {Array} experiments 实验列表
 */
const deleteExperimentSubTable = async (experiments) => {
  if (!experiments?.length) {
    console.log("⚠️ 无实验数据，跳过实验子表删除");
    return;
  }

  console.log(`🧪 开始删除实验子表，实验数量: ${experiments.length}`);
  console.log("实验列表:", experiments);

  // 循环删除每个实验记录
  for (let i = 0; i < experiments.length; i++) {
    const experiment = experiments[i];

    if (!experiment.order_experiment_id) {
      console.warn(`⚠️ 跳过无效实验记录 [${i + 1}]:`, experiment);
      continue;
    }

    try {
      console.log(`🧪 删除实验记录 [${i + 1}/${experiments.length}]:`, {
        order_experiment_id: experiment.order_experiment_id,
        experiment_id: experiment.experiment_id,
        use_months: experiment.use_months,
      });

      // 调用API删除实验子表记录
      const result = await api.apiOrderExperimentDeletePost({
        order_experiment_id: experiment.order_experiment_id,
      });

      console.log(`✅ 实验记录 [${i + 1}] 删除成功:`, result);
    } catch (error) {
      console.error(`❌ 实验记录 [${i + 1}] 删除失败:`, error);
      throw new Error(`删除实验记录失败 [${i + 1}]: ${error.message}`);
    }
  }

  console.log("✅ 实验子表删除完成");
};
</script>
